package com.meiyuetao.myt.job;

import com.jd.open.api.sdk.internal.util.StringUtil;
import com.meiyuetao.o2o.entity.SharedPosts;
import com.meiyuetao.o2o.entity.SharedPostsFailImgs;
import com.meiyuetao.o2o.service.SharedPostsFailImgsService;
import com.meiyuetao.o2o.service.SharedPostsService;
import com.meiyuetao.util.FileUploadUtil;
import com.meiyuetao.util.MediaApi;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.schedule.BaseQuartzJobBean;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.JobExecutionContext;

import java.io.InputStream;
import java.util.List;

/**
 * Created by zhuhui on 16-1-25.
 */
public class ReloadPostFailImgs extends BaseQuartzJobBean {

    private final static Logger logger = LoggerFactory.getLogger(C2cUpdateComPic.class);

    @Override
    protected void executeInternalBiz(JobExecutionContext jobExecutionContext) {
        logger.debug("ReloadPostFailImgs executing...");
        SharedPostsFailImgsService sharedPostsFailImgsService = this.getSpringBean(SharedPostsFailImgsService.class);
        SharedPostsService postsService = this.getSpringBean(SharedPostsService.class);
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(PropertyFilter.MatchType.EQ, "hasPerformed", false));
        List<SharedPostsFailImgs> sharedPostsFailImgsList = sharedPostsFailImgsService.findByFilters(groupPropertyFilter);
        if (CollectionUtils.isNotEmpty(sharedPostsFailImgsList)) {
            for (SharedPostsFailImgs spfi : sharedPostsFailImgsList) {
                InputStream is = MediaApi.getMedia(spfi.getToken(), spfi.getServerId());
                String md5 = FileUploadUtil.uploadPic(spfi.getServerId(), is);
                if (!StringUtil.isEmpty(md5)) {
                    SharedPosts post = spfi.getPost();
                    if ("img1".equals(spfi.getImgIndex())) {
                        post.setPostsSharedPic1(md5);
                    } else if ("img2".equals(spfi.getImgIndex())) {
                        post.setPostsSharedPic2(md5);
                    } else if ("img3".equals(spfi.getImgIndex())) {
                        post.setPostsSharedPic3(md5);
                    }
                    spfi.setHasPerformed(true);
                    sharedPostsFailImgsService.save(spfi);
                    postsService.save(post);
                }
            }
            logger.debug("ReloadPostFailImgs executing end");
        }
    }
}
